<?php
namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Jobs\ExploreAcceptJob;
use App\Models\Common\Common;
use App\Models\Common\File;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ExploreAcceptController extends ClientController
{
    /**
     * 接单
     */
    public function index()
    {
        /**
         * 验证
         */
        $all = $this->all;
        if(empty($all['eo_id']) || empty($all['clock_in_img_src']) ){
            return $this->setReturnJson(-1,'缺少参数');
        }
        $eo_id = $all['eo_id'];
        $clock_in_img_src = $all['clock_in_img_src'];// 打卡截图

        // 验证接单操作
        try{
            // 查询当前订单信息
            $order_message = DB::table('explore_order')->where('eo_id','=',$eo_id)->first();
            $order_message = json_decode(json_encode($order_message),true);

            // 不允许自己抢自己的订单
            if($order_message['we_id'] === $this->we_id){
                return $this->setReturnJson(-1,'不能探店自己的店铺哦~');
            }

            // 查询当前openid接单当前的接单次数
            $count = DB::table('explore_work')
                ->where('receiver_we_id','=',$this->we_id)
                ->where('created_at' ,'>',date('Y-m-d 00:00:00'))
                ->count();
            if ($count >= 3 && env("APP_ENV") === "production") {
                return $this->setReturnJson(-1,'每日限接3单，您已超出接单上限，请明天再来。');
            }

            // 查询我的达人信息
            $talent_message = DB::table('talent')->where('we_id','=',$this->we_id)->first();
            $talent_message = json_decode(json_encode($talent_message), true);

            if($talent_message['status'] !== 1){
                return $this->setReturnJson(-1,'您的账号未通过认证');
            }
            if(!$talent_message['intelligent']){
                return $this->setReturnJson(-1,'您不是来飞网的认证达人，暂时不能接单');
            }
            if($talent_message['channel_id'] < $order_message['channel_id']){
                return $this->setReturnJson(-1,'您的等级不符合要求');
            }

            // 查询达人是否有探店过这个店铺的记录
            $worked = DB::table('explore_work')
                ->where('shop_id','=',$order_message['shop_id']) // 店铺id
                ->where('receiver_we_id','=',$this->we_id)
                ->where('status','<>',Data::DATA_DB_EXPLORE_WORK_STATUS_ERROR)
                ->count();
            if($worked){
                return $this->setReturnJson(-1,'您已经接单过此店铺，请勿重复接单');
            }

//            // 验证用户地址
//            $userInfo = $this->userInfo;
//            $address_city = $userInfo['address_city'];
//            $address_updated_at = $userInfo['address_updated_at'];
//            if(!$address_city){
//                return $this->setReturnJson(-1,'您未授权获取您的地理位置，请打开手机定位功能并重新打开此页面，同意授权地理位置。');
//            }
//            if(strtotime($address_updated_at) < strtotime("-1 day")){
//                return $this->setReturnJson(-1,'距离您上次定位已超过24小时，请关闭并重新打开此页面以刷新定位');
//            }
//            $shop_city = DB::table('shop')->where('shop_id','=',$order_message['shop_id'])->value('city');
//            if($address_city !== $shop_city){
//                return $this->setReturnJson(-1,'您当前的定位不在店铺所在城市');
//            }

            // 验证订单挂起人
            if($this->we_id !== (int)Redis::get('explore_order_task_' . $eo_id)){
                return $this->setReturnJson(-1,'您的抢单已超时，请返回上一页重试');
            }

        }catch (\Exception $e){
            Log::error(ExploreAcceptController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'接单失败，请刷新当前页面重试');
        }

        /**
         * 开始处理操作
         */
        try{
            DB::beginTransaction();
            // 再次查询当前订单的店铺状态(X锁)
            $order_message = DB::table('explore_order')->where('eo_id','=',$eo_id)->lockForUpdate()->first();
            $order_message = json_decode(json_encode($order_message),true);
            // 检查这个订单状态
            $order_status = $order_message['status'];
            // 订单是否已经被抢光
            if($order_status === Data::DATA_DB_EXPLORE_ORDER_STATUS_SUCCESS){
                DB::rollBack();
                return $this->setReturnJson(-1,'当前订单已抢单结束，下次早点来哦~');
            }
            // 检查订单超时
            if($order_status === Data::DATA_DB_EXPLORE_ORDER_STATUS_PARTIAL_SUCCESS || $order_status === Data::DATA_DB_EXPLORE_ORDER_STATUS_FAILED){
                DB::rollBack();
                return $this->setReturnJson(-1,'当前订单时间已超时，请在商家发布后的24小时内接单哦');
            }
            $order_price = DB::table('explore_channel')->where('channel_id','=',$order_message['channel_id'])->value('price');

            // 修改当前订单数量信息
            $update_arr = [
                'remaining_num'=>$order_message['remaining_num']-1,
                'distribution_num'=>$order_message['distribution_num']+1,
                'pending_num'=>$order_message['pending_num']+1,
            ];
            // 如果数量相同，直接保存订单为已完成状态
            if($order_message['total_num'] === $order_message['distribution_num']+1){
                $update_arr['status'] = Data::DATA_DB_EXPLORE_ORDER_STATUS_SUCCESS;
            }
            DB::table('explore_order')->where('eo_id','=',$eo_id)->update($update_arr);
            // 记录订单操作日志
            DB::table('explore_order_log')->insert([
                'eo_id'=>$eo_id,
                'action'=>Data::DATA_DB_EXPLORE_ORDER_ACTION_RECEIVE,// 接单
                'we_id'=>$this->we_id,
            ]);
            if(isset($update_arr['status']) && $update_arr['status'] === Data::DATA_DB_EXPLORE_ORDER_STATUS_SUCCESS){
                DB::table('explore_order_log')->insert([
                    'eo_id'=>$eo_id,
                    'action'=>Data::DATA_DB_EXPLORE_ORDER_ACTION_SUCCESS,//接单全部完成
                    'we_id'=>$this->we_id,
                ]);
            }

            // 接单并对应到接单账号
            $work_id = DB::table('explore_work')->insertGetId([
                'eo_id'=>$order_message['eo_id'],
                'work_no'=>self::getWorkNo(),
                'shop_id'=>$order_message['shop_id'],
                'apply_we_id'=>$order_message['we_id'],
                'receiver_we_id'=>$this->we_id,
                'talent_id'=>$talent_message['talent_id'],
                'settlement_amount'=>$order_price,
            ]);
            // 记录工单操作日志
            DB::table('explore_work_log')->insert([
                'work_id'=>$work_id,
                'action'=>Data::DATA_DB_EXPLORE_WORK_ACTION_INIT,
                'we_id'=>$this->we_id,
                'remark'=>'用户【'.$this->nickname.'】接单',
            ]);
            // 保存图片
            $file_path = 'images/work/' . $work_id;
            $img = File::saveMedia($clock_in_img_src, $file_path);
            DB::table('explore_work')->where('work_id','=',$work_id)->update(['clock_in_img'=>$img]);
            ExploreAcceptJob::dispatch($work_id)->delay(now()->addSeconds(Period::getSetting('EXPLORE_UPLOAD_LIMIT_TIME'))); // 加入队列，可投稿时提醒
            Redis::del('explore_order_task_we_id_'.$this->we_id);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            Log::error(ExploreAcceptController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'接单失败，请刷新当前页面重试');
        }
        try{
            // 发送接单微信通知
            $data = [
                'first' => '您好，您发布的探店任务已有达人接单，请点击查看详情。',
                'keyword1' => $talent_message['account_name'],
                'keyword2' => '-',
                'keyword3' => date('Y-m-d H:i:s'),
                'remark' => '感谢您的使用。',
            ];
            //发送通知
            $openid = DB::table('lottery_users')->where('we_id','=',$order_message['we_id'])->value('openid');
            Common::sendLaifeiMessage($openid,'explore_invite',$data,'/history?tab=1');
        }catch (\Exception $e) {
            Log::error(ExploreAcceptController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(0,'接单成功');
        }
        return $this->setReturnJson(0,'恭喜您，抢单成功');
    }

    /**
     * 查询可用的工单编号
     * @return string
     */
    public static function getWorkNo()
    {
        $prefix = env("WECHAT_PAYMENT_PREFIX"); // 订单编号前缀，用于区分测试和生产
        $date = date('Ymd');
        $maxNo = DB::table('explore_work')
            ->where('work_no','like',$prefix.$date.'%')
            ->latest()
            ->value('work_no');
        if($maxNo){
            $no = substr($maxNo,9);
            $no = (int)$no + 1;
            $no = (string)$no;
            $no = str_pad($no,6,'0',STR_PAD_LEFT);
            $work_no = $date.$no;
        } else {
            $work_no = $date.'000001';
        }
        return $prefix.$work_no;
    }

}
